package com.syqc.monitor.ui.cars

import android.app.Activity
import android.content.Context
import android.graphics.drawable.ColorDrawable
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.widget.*
import androidx.core.content.ContextCompat
import androidx.core.view.isVisible
import androidx.recyclerview.widget.LinearLayoutManager
import com.google.android.material.tabs.TabLayout
import com.gyf.immersionbar.ImmersionBar
import com.syqc.comlib.rx.doAfterChanged
import com.syqc.comlib.utils.loadGif
import com.syqc.comlib.utils.toast
import com.syqc.entity.GpsDetail
import com.syqc.interfaces.SimpleTabLayoutListener
import com.syqc.monitor.R
import com.syqc.monitor.databinding.PopupCarsBinding
import com.syqc.utils.ToolsUtil

/** @Author pc_hfjs @Date 2022/3/8 11:35 @Desc */
class CarsPopup(private val context: Context) : PopupWindow() {
    private val mAdapter by lazy { CarsAdapter() }
    private val layoutInflater by lazy { LayoutInflater.from(context) }
    private val binding = PopupCarsBinding.inflate(LayoutInflater.from(context))
    private val titles = ArrayList<String>()
    private var index = 0
    private val mData = ArrayList<ArrayList<GpsDetail>>()
    private val queryList = ArrayList<GpsDetail>()
    private var search = ""
    var isPlate: Boolean = true

    private val emptyView by lazy {
        val view = layoutInflater.inflate(
            R.layout.layout_empty_view,
            binding.recycler,
            false
        )
        view.findViewById<TextView>(R.id.tv_empty)
            .setTextColor(ContextCompat.getColor(context, R.color.white))
        view.findViewById<ImageView>(R.id.ivNoData).loadGif(context, R.mipmap.ic_empty)

        view
    }

    init {
        contentView = binding.root
        binding.tvClose.setOnClickListener {
            dismiss()
        }
        initView()
        //设置SelectPicPopupWindow弹出窗体的宽
        width = LinearLayout.LayoutParams.MATCH_PARENT
        //设置SelectPicPopupWindow弹出窗体的高
        height = LinearLayout.LayoutParams.MATCH_PARENT
        isFocusable = true //popupwindow设置焦点
        setBackgroundDrawable(ColorDrawable(-0x56000000)) //设置背景
        animationStyle = R.style.PopupAnimation
    }

    private fun initView() {
        val stringArray = context.resources.getStringArray(R.array.tab_list_monitor)
        titles.addAll(stringArray)
        titles.forEach {
            binding.tabLayout.addTab(binding.tabLayout.newTab().setText(it))
        }
        binding.recycler.layoutManager = LinearLayoutManager(context)
        binding.recycler.adapter = mAdapter
        binding.tabLayout.addOnTabSelectedListener(object : SimpleTabLayoutListener {
            override fun onTabSelected(tab: TabLayout.Tab?) {
                index = tab?.position ?: 0
                binding.recycler.scrollToPosition(0)
                showData(mData[index])
            }
        })

        binding.ivClear.setOnClickListener {
            binding.editSearch.setText("")
        }

        binding.editSearch.doAfterChanged {
            search = it
            if (it.isNotEmpty()) {
                search(it)
                binding.tabLayout.isVisible = false
            } else {
                binding.tabLayout.isVisible = true
                showData(mData[index])
            }
        }

        mAdapter.setOnItemClickListener { adapter, view, position ->
            val carInfo = mAdapter.data[position]
            if (ToolsUtil.isNoLocation(carInfo.state) || carInfo.glat.isNullOrEmpty()) {
                R.string.toast_no_location_msg.toast(context)
                return@setOnItemClickListener
            }
            mCallback?.callback(carInfo.carId)
        }
    }

    fun resetTabLayout(nums: List<String>) {
        titles.forEachIndexed { index, title ->
            binding.tabLayout.getTabAt(index)?.text = "$title(${nums[index]})"
        }
    }

    fun resetTabLayouts(nums: List<Int>) {
        titles.forEachIndexed { index, title ->
            binding.tabLayout.getTabAt(index)?.text = "$title(${nums[index]})"
        }
    }

    fun refreshData(data: List<ArrayList<GpsDetail>>, isPlate: Boolean) {
        mAdapter.isPlate = isPlate
        this.isPlate = isPlate
        mData.clear()
        mData.addAll(data)

        queryList.clear()
        queryList.addAll(data[0])
        if (search.isEmpty()) showData(data[index]) else search(search)
    }

    private fun showData(data: MutableList<GpsDetail>) {
        if (data.isNullOrEmpty())
            mAdapter.setEmptyView(emptyView)
        mAdapter.setList(data)
    }

    fun show(view: View) {
        if (!isShowing)
            showAtLocation(view, Gravity.CENTER, 0, 0)
    }

    /**
     * ******************************筛选数据**************************************************
     */
    private fun search(key: String) {
        val upKey = key.uppercase()
        val filter = queryList.filter { it.carPlate.uppercase().contains(upKey) }
        showData(filter.toMutableList())
    }

    /**
     * ***************************************选车回调*******************************************
     */
    private var mCallback: CallBack? = null

    interface CallBack {
        fun callback(carId: String)
    }

    fun setCallBack(callback: CallBack) {
        mCallback = callback
    }


    fun updateView() {
        val navigationBarHeight: Int = ImmersionBar.getNavigationBarHeight(context)
        ImmersionBar.setTitleBar(context as Activity, binding.llAll)
        binding.llAll.post {
            val layoutParams =
                binding.llAll.layoutParams as FrameLayout.LayoutParams
            layoutParams.setMargins(0, 0, 0, navigationBarHeight)
            binding.llAll.layoutParams = layoutParams
        }
    }

}